package com.baseDemo.web.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baseDemo.web.entity.UploadImageEntity;
import com.baseDemo.web.server.SystemServer;
import com.baseDemo.web.service.uploadimage.UploadImageService;

@Controller
@RequestMapping(value = "/uploadimage")
public class UploadImageController {
	@Resource
	UploadImageService uploadImageService;

	@RequestMapping(value = "/upload")
	public @ResponseBody
	String upload(UploadImageEntity uploadImageEntity) {
		return uploadImageService.upload(uploadImageEntity);
	}

	@RequestMapping(value = "/showImage/{ownerEntity}/{ownerId}")
	public void showImage(@PathVariable("ownerEntity") String ownerEntity,@PathVariable("ownerId") String ownerId,HttpServletRequest request,
			HttpServletResponse reponse) throws IOException {
		UploadImageEntity temp = uploadImageService.getImage(ownerEntity, ownerId);
		InputStream is ;
		if(temp!=null){
			is = new ByteArrayInputStream(temp.getImageFile());
		}else{
			File file = new File(request.getSession().getServletContext().getRealPath("")+SystemServer.getInstance().get("DEFAULTIMAGE"));
			is = new FileInputStream(file);
		}
		ServletOutputStream out = null;
		reponse.setContentType("application/octet-stream;charset=UTF-8");
		byte[] buff = new byte[2048];
		int size = 0;
		out = reponse.getOutputStream();
		while (is != null && (size = is.read(buff)) != -1) {
			out.write(buff, 0, size);
		}
		out.flush();
		out.close();
	}
}
